from machine import Timer,PWM
import time
from fpioa_manager import fm
from machine import UART

#占空比
ch_duty = [7.5, 7.5, 7.5, 7.5, 7.5, 7.5]


#初始化定时器
tim1 = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
tim2 = Timer(Timer.TIMER0, Timer.CHANNEL1, mode=Timer.MODE_PWM)
tim3 = Timer(Timer.TIMER0, Timer.CHANNEL2, mode=Timer.MODE_PWM)
tim4 = Timer(Timer.TIMER0, Timer.CHANNEL3, mode=Timer.MODE_PWM)
tim5 = Timer(Timer.TIMER1, Timer.CHANNEL0, mode=Timer.MODE_PWM)
tim6 = Timer(Timer.TIMER1, Timer.CHANNEL1, mode=Timer.MODE_PWM)
rgb_g_tim = Timer(Timer.TIMER1, Timer.CHANNEL2, mode=Timer.MODE_PWM)
#初始化通道
ch1 = PWM(tim1, freq=50, duty=50, pin=6)
ch2 = PWM(tim2, freq=50, duty=50, pin=7)
ch3 = PWM(tim3, freq=50, duty=50, pin=8)
ch4 = PWM(tim4, freq=50, duty=50, pin=9)
ch5 = PWM(tim5, freq=50, duty=50, pin=10)
ch6 = PWM(tim6, freq=50, duty=50, pin=15)
rgb_g_ch = PWM(rgb_g_tim, freq=1000, duty=0, pin=12)

#初始化串口
fm.register(25, fm.fpioa.UART2_TX, force=True)
fm.register(24, fm.fpioa.UART2_RX, force=True)
#串口初始化
uart_handler = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)



#PWM控制
def pwm_ctrl():
    global ch_duty
    global ch1
    global ch2
    global ch3
    global ch4
    global ch5
    global ch6
    #设置占空比
    ch1.duty(ch_duty[0])
    ch2.duty(ch_duty[1])
    ch3.duty(ch_duty[2])
    ch4.duty(ch_duty[3])
    ch5.duty(ch_duty[4])
    ch6.duty(ch_duty[5])


def uart_data_parse(data_str):
    #print (data_str[:5], data_str[len(data_str)-3:])
    if ('START' == data_str[:5]) and ('END' in data_str[len(data_str)-5:]):
        str_list = ''.join(data_str[7:len(data_str)-5].split('::')).split(':')
        for steer_num in str_list:
            #print(steer_num)
            steer = steer_num.split('-')
            print (steer[0], steer[1])
            ch_duty[int(steer[0])] = float(steer[1])

#串口控制
def uart_ctrl():
    global uart_handler
    #write_str = 'hello world'
    #传输串口数据
    #uart_handler.write(write_str)
    if uart_handler.any():
        read_data = uart_handler.readline().decode('utf-8')
        if read_data:
            print (read_data)
            uart_data_parse(read_data)
            #read_str = read_data.decode('utf-8')
            #print("string = ", read_str)

rgb_g_cnt = 0
rgb_g_flg = 0
def rgb_ctrl():
    global rgb_g_cnt
    global rgb_g_flg
    global rgb_g_ch

    if (rgb_g_flg == 1):
        rgb_g_cnt = rgb_g_cnt - 0.1
    else:
        rgb_g_cnt = rgb_g_cnt + 0.1

    if (rgb_g_cnt >= 99.9):
        rgb_g_flg = 1
    elif (rgb_g_cnt <= 0.99):
        rgb_g_flg = 0

    #print (rgb_g_cnt)
    rgb_g_ch.duty(rgb_g_cnt)



if __name__ == '__main__':
    while True:
        uart_ctrl()
        pwm_ctrl()
        rgb_ctrl()
        time.sleep(0.001)



